/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview step 3 of the OAuth 2.0 client side flow tutorial.
 * @author silvano.luciani@gmail.com (Silvano Luciani)
 */

/**
 * Executes the flow for the step.
 */
function startFlow() {
  authorize();
}

/**
 * Write the value of the access token into an alert popup if a fragment is
 * present, otherwise redirects to the authorization server.
 */
function authorize() {
  var uri = new goog.Uri(window.location);
  if (uri.hasFragment()) {
    var queryData = new goog.Uri.QueryData(uri.getFragment());
    alert(queryData.get('access_token'));
  } else {
    redirectToAuth();
  }
}

/**
 * Redirects to the authorization server.
 */
function redirectToAuth() {
  var authUri = new goog.Uri(conf.AUTH_URI);
  authUri.setParameterValue('scope', conf.AUTH_SCOPE);
  authUri.setParameterValue('redirect_uri', conf.REDIRECT_URI);
  authUri.setParameterValue('response_type', 'token');
  authUri.setParameterValue('client_id', conf.CLIENT_ID);
  window.location = authUri.toString();
}

